package com.bingo.demo.config;

import com.bingo.demo.pojo.User;
import com.bingo.demo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    //授权
    //有权限判断时才会执行这个方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到当前请求登录的用户对象
        Subject subject= SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        //拿到数据库中查出的user对象
        info.addStringPermission(user.getAuthority());
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //首先执行认证
        //此方法中执行认证操作
        UsernamePasswordToken userToken=(UsernamePasswordToken) authenticationToken;
        User user = userService.findUserByUsername(userToken.getUsername());
        if((user != null)&&(user.getPassword().equals(userToken.getPassword()))){
            Subject subject= SecurityUtils.getSubject();
        }
        if(user == null){
            return null;//此时抛出UnknownAccountException异常,即用户名错误
        }
        //只需要提供密码，shiro自动认证
        return new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());
    }
}
